package com.ihunanren.weixin.module.action.school;

import static com.google.common.base.Strings.isNullOrEmpty;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.citrus.service.form.Group;
import com.alibaba.citrus.service.uribroker.URIBrokerService;
import com.alibaba.citrus.turbine.Context;
import com.alibaba.citrus.turbine.Navigator;
import com.alibaba.citrus.turbine.dataresolver.FormGroup;
import com.alibaba.citrus.turbine.uribroker.uri.TurbineContentURIBroker;
import com.ihunanren.biz.common.SpringEmail;
import com.ihunanren.biz.result.Result;
import com.ihunanren.biz.weixin.ao.ISchoolCurriculumAO;
import com.ihunanren.common.CalendarUtil;
import com.ihunanren.common.auth.DES;
import com.ihunanren.dao.pojo.SchoolCurriculumDefinedDO;
import com.ihunanren.dao.pojo.SchoolCurriculumInfoDO;
import com.ihunanren.webx.GroupUtils;
import com.ihunanren.webx.SessionExtra;
import com.ihunanren.webx.SessionKeeper;
import com.ihunanren.webx.UserTrackInfo;

public class SchoolCourseAction {
	@Autowired
	private HttpServletRequest request;
	@Autowired
	private ISchoolCurriculumAO schoolCurriculumAO;
	@Autowired
	private SpringEmail springEmail;
	@Autowired
	private URIBrokerService uriBrokerService;

	public void doRegisterVolunteer(@FormGroup("SchoolCurriculumDefinedGroup") Group group,
			Navigator nav, Context context) {
		UserTrackInfo trackInfo = new UserTrackInfo(request);
		
		SchoolCurriculumDefinedDO definedDO = createSchoolCurriculumDefinedDO(group,trackInfo);
		Result result = schoolCurriculumAO.insertStudent(trackInfo.getIpAddress(),definedDO);
		
		if(result.isSuccess()){
			springEmail.send(definedDO.getName(), definedDO.getEmail(), getSetPasswordUrl(definedDO));
			context.put("registerSuccess", "注册成功！账户激活链接已发至邮箱："+ definedDO.getEmail()+"");
		}else{
			context.put("errorMsg", result.getDefaultErrorMsg());
		}
	}
	
	private String getSetPasswordUrl(SchoolCurriculumDefinedDO definedDO){
		StringBuilder sb = new StringBuilder();
		sb.append(definedDO.getName()).append(";").append(definedDO.getEmail())
				.append(";").append(definedDO.getDiyName());
		String sendTime = CalendarUtil.formatDate(new Date(), CalendarUtil.TIME_PATTERN);
		sb.append(";").append(sendTime);
		String sign = DES.encrypt(sb.toString(), DES.DEFAULT_KEY);
		TurbineContentURIBroker broker = (TurbineContentURIBroker) uriBrokerService.getURIBroker("weixinContent");
		String str = broker.getServerURI();
		return str + "/school/password.htm?sign="+sign;
	}
	
	/**设置密码*/
	public void doRegisterAuth(@FormGroup("SchoolCurriculumPasswordGroup") Group group,
			Navigator nav, Context context) {
		GroupUtils groupUtils = new GroupUtils(group);
		
		String password = groupUtils.getString("password");
		String password2 = groupUtils.getString("password_again");
		
		if(!isNullOrEmpty(password2) && !password2.equals(password)){
			context.put("errorMsg", "两次密码不匹配");
			return ;
		}
		
		String email = groupUtils.getString("email");
		
		if(!isNullOrEmpty(password2) && password2.equals(password) && !isNullOrEmpty(email)){
			UserTrackInfo trackInfo = new UserTrackInfo(request);
			String ip = trackInfo.getIpAddress();
			boolean b = schoolCurriculumAO.updateStudentPassword(email, ip, password);
			if(b){
				nav.forwardTo("/school/school_course");
				return;
			}
		}
		context.put("errorMsg", "非法请求");
	}
	
	
	public void doLogin(@FormGroup("SchoolCurriculumLoginGroup") Group group,
			Navigator nav, Context context) {
		
		GroupUtils groupUtils = new GroupUtils(group);
		String email = groupUtils.getString("email");
		String password = groupUtils.getString("password");
		
		SchoolCurriculumDefinedDO curriculumInfoDO = schoolCurriculumAO.getByEmail(email);
		if(curriculumInfoDO != null){
			if(curriculumInfoDO.getStatus() == 0){
				context.put("loginError", "账号没有激活");
				nav.forwardTo("/school/login");
				return;
			}else if(! curriculumInfoDO.getPassword().equals(password)){
				context.put("loginError", "密码不正确");
				nav.forwardTo("/school/login");
				return;
			}else{
				SessionExtra extra = new SessionExtra(request);
				extra.setSession(SessionKeeper.LOGIN_USER, curriculumInfoDO.getName());
				extra.setSession(SessionKeeper.LOGIN_USER_DEFINEDID, curriculumInfoDO.getId().toString());
			}
		}else{
			context.put("loginError", "账号不存在");
			nav.forwardTo("/school/login");
		}
	}
	
	
	public void doSaveCourse(@FormGroup("SchoolCurriculumInfoGroup") Group group,
			Navigator nav, Context context) {
		UserTrackInfo trackInfo = new UserTrackInfo(request);

		if (!trackInfo.isLogin()) {
			nav.forwardTo("/school/login");
			return;
		}
		GroupUtils groupUtils = new GroupUtils(group);
		SchoolCurriculumInfoDO infoDO = createSchoolCurriculumInfoDO(groupUtils, trackInfo);
		
		Result result = schoolCurriculumAO.insertSchoolCurriculumInfo(infoDO);
		if(!result.isSuccess()){
			context.put("errorMsg", result.getDefaultErrorMsg().toString());
		}
		
	}
	
	private SchoolCurriculumInfoDO createSchoolCurriculumInfoDO(GroupUtils groupUtils, UserTrackInfo trackInfo) {
		SchoolCurriculumInfoDO infoDO = new SchoolCurriculumInfoDO();
		infoDO.setDefinedId(groupUtils.getLong("definedId"));
		infoDO.setLession(groupUtils.getString("lession"));
		infoDO.setLessionSection(groupUtils.getInt("lessionSection"));
		infoDO.setLocation(groupUtils.getString("location"));
		infoDO.setRemark(groupUtils.getString("remark"));
		infoDO.setTeacher(groupUtils.getString("teacher"));
		infoDO.setWeek(groupUtils.getInt("week"));
		infoDO.setTimeStart(groupUtils.getString("timeStart"));
		infoDO.setTimeEnd(groupUtils.getString("timeEnd"));
		infoDO.setDefinedId(trackInfo.getUserDefinedId());
		return infoDO;
	}
	
	private SchoolCurriculumDefinedDO createSchoolCurriculumDefinedDO(Group group,UserTrackInfo trackInfo){
		GroupUtils groupUtils = new GroupUtils(group);
		
		SchoolCurriculumDefinedDO definedDO = new SchoolCurriculumDefinedDO();
		definedDO.setClassName(groupUtils.getString("className"));
		definedDO.setDeptName(groupUtils.getString("deptName"));
		definedDO.setName(groupUtils.getString("name"));
		definedDO.setDiyName(groupUtils.getString("diyName"));
		definedDO.setRemark(groupUtils.getString("remark"));
		definedDO.setSchoolId(groupUtils.getInt("schoolId"));
		definedDO.setEmail(groupUtils.getString("email"));
		definedDO.setStatus(0);
		return definedDO;
	}
}
